package com.jackrain.nea.ad.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.ad.api.AdactionDeleteCmd;
import com.jackrain.nea.ad.mapper.AdactionMapper;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * AdactionDeleteCmdImpl class
 *
 * @author bigzhi
 * @date 2017/11/22
 */

@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "ad")
public class AdactionDeleteCmdImpl extends CommandAdapter implements AdactionDeleteCmd {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ValueHolder execute(QuerySession querySession) throws NDSException {
        AdactionMapper adactionMapper = ApplicationContextHandle.getBean(AdactionMapper.class);
        ValueHolder vh = new ValueHolder();
        DefaultWebEvent event = querySession.getEvent();

        //TODO 获取参数
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(event.getParameterValue("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        Long objid = param.getLong("objid");

        if (objid > 0) {
            //TODO 删除

            //记录不存在
            if (adactionMapper.findCountById(objid) == 0) {
                vh.put("code", -1);
                vh.put("message", Resources.getMessage("当前记录已不存在！", querySession.getLocale()));
                return vh;
            }

            //执行数据库删除操作
            adactionMapper.delete(objid);

        } else {
            //无效ID，报错
            vh.put("code", -1);
            vh.put("message", Resources.getMessage("未执行操作：", querySession.getLocale()) + Resources.getMessage("无效的ID值", querySession.getLocale()));
            return vh;
        }

        //TODO 返回结果信息
        vh.put("code", 0);
        vh.put("message", Resources.getMessage("成功", querySession.getLocale()));
        return vh;
    }

}
